import React, { useCallback, useEffect, useState } from "react";
import { Form, Input, Select, Tooltip } from "antd";
import environmentStore from "../../../../../support/environment/store/environmentStore";
import {observer} from "mobx-react";

const { Option } = Select;

const ApiServerUrlSelect = () => {
    const { testEnvUrl, getTestEnvUrl,selectEnvInfo } = environmentStore;

    /**
     * 测试环境切换
     */
    const renderHostSelect = useCallback(() => {
        // 无环境列表时显示输入框
        if (!selectEnvInfo.serverList || selectEnvInfo.serverList.length === 0) {
            return (
                <Form.Item
                    name="host"
                    className='formItem'
                    rules={[
                        { type: 'url', message: '请输入有效的 URL 地址' },
                    ]}
                >
                    <Input placeholder="请输入HTTP开头的完整URL" />
                </Form.Item>
            );
        }

        // 只有一个环境时显示固定值
        if (selectEnvInfo.serverList.length === 1) {
            getTestEnvUrl(selectEnvInfo.serverList[0].url);
            return (
                <Tooltip placement="top" title="请从环境管理修改">
                    <div className="test-host-url">
                        {selectEnvInfo.serverList[0].url}
                    </div>
                </Tooltip>
            );
        }

        // 多个环境时显示下拉框
        const defaultValue = selectEnvInfo.serverList.find(item => item.name === "默认服务")?.url || selectEnvInfo.serverList[0].url;

        return (
            <Select
                className="test-host-select"
                onChange={(value) => {
                    getTestEnvUrl(value);
                }}
                defaultValue={defaultValue}
            >
                {selectEnvInfo.serverList.map((item, index) => (
                    <Option key={index} value={item.url}>
                        {item.url}
                    </Option>
                ))}
            </Select>
        );
    }, [selectEnvInfo.serverList, testEnvUrl, getTestEnvUrl]);

    return renderHostSelect();
};

export default observer(ApiServerUrlSelect);